package io.gitee.minelx.filesystem;

import io.gitee.minelx.filesystem.init.OpenPolicy;
import io.gitee.minelx.filesystem.init.PathType;

import java.util.Objects;
import java.util.stream.Stream;

import static java.util.Arrays.stream;

public class Directory {

	private final Path path;

	private final Locator locator;

	private Directory(Path path) {
		this.path = path;
		locator = new Locator(path.getPathMethodProviderFactory(), path.description());
	}

	public String[] childrenNames() {
		return path.getPathMethodProvider().listDir();
	}

	public Stream<Path> children() {
		return childrenStream();
	}

	public boolean empty() {
		return childrenNames().length == 0;
	}

	public void clear() {
		childrenStream().forEach(Path::delete);
	}

	private Stream<Path> childrenStream() {
		return stream(childrenNames()).map(childName -> child().path(childName));
	}

	public Path path() {
		return path;
	}

	public Locator child() {
		return locator;
	}

	public static Directory create(Path path, OpenPolicy openPolicy) {
		openPolicy.open(path, PathType.DIR);
		return new Directory(path);
	}

	@Override
	public boolean equals(Object o) {
		if (this == o) return true;
		if (o == null || getClass() != o.getClass()) return false;
		Directory directory = (Directory) o;
		return path.equals(directory.path) && locator.equals(directory.locator);
	}

	@Override
	public int hashCode() {
		return Objects.hash(path, locator);
	}

	@Override
	public String toString() {
		return "Directory{" +
				"path=" + path +
				", locator=" + locator +
				'}';
	}
}
